package com.zy.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.entity.Email;
import com.zy.entity.JsonResult;
import com.zy.mapper.EmailMapper;
import com.zy.service.impl.EmailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/app")
public class EmailController {
    JSONObject jsonObject = new JSONObject();
    @Autowired
    EmailMapper emailMapper;
    @Autowired
    private EmailServiceImpl emailService;

    /**
     * 查询个人未读邮件
     *
     * @param uid
     * @return com.zy.entity.JsonResult
     * @author 小宁
     * @date 2021-04-07 15:17
     */
    @GetMapping("/getEmailList")
    @ResponseBody
    public JsonResult getEmailList(Integer uid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", uid);
        queryWrapper.orderByDesc("time");
        List<Email> emailList = emailService.list(queryWrapper);
        System.out.println(emailList);
        Map<String, List<Email>> groups = emailList.stream().collect(Collectors.groupingBy(Email::getDate, Collectors.toList()));
        String res = jsonObject.toJSONStringWithDateFormat(groups, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
        return new JsonResult("200", "", res);
    }

    /**
     * 更新邮件读取状态
     *
     * @param id
     * @return com.zy.entity.JsonResult
     * @author 小宁
     * @date 2021-04-07 15:16
     */
    @GetMapping("/upEmail")
    @ResponseBody
    public JsonResult upEmail(int id) {
        Email email = emailService.getById(id);
        if (email.getFlag() != 1) {
            email.setFlag(1);
            emailService.updateById(email);
        }
        String res = jsonObject.toJSONStringWithDateFormat(email, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);
        return new JsonResult("200", "", res);
    }

    /**
     * 查询个人未读邮件数量
     *
     * @param uid
     * @return com.zy.entity.JsonResult
     * @author 小宁
     * @date 2021-04-07 15:17
     */
    @GetMapping("/getEmailNum")
    @ResponseBody
    public JsonResult getEmailNum(Integer uid) {
        Integer emailNum = emailMapper.getEmailNum(uid);
        return new JsonResult("200", "", emailNum);
    }
}
